package com.ear.orange.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ear.orange.common.BaseContext;
import com.ear.orange.common.Result;
import com.ear.orange.entity.AddressBook;
import com.ear.orange.mapper.AddressBookMapper;
import com.ear.orange.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author orange
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public void setUserAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        this.save(addressBook);
    }

    @Override
    public void setDefaultAddress(AddressBook addressBook) {
        //用户id
        Long userId = BaseContext.getCurrentId();
        //将用户id下的所有的地址先修改为不默认
        addressBookMapper.setDefaultAddress(userId);
        //再将指定的订单设为默认
        Long id = addressBook.getId();
        addressBookMapper.updateDefaultAddress(userId, id);
    }

    @Override
    public Result getAddressById(Long id) {
        AddressBook address = addressBookMapper.getAddressById(id);
        if (BeanUtil.isEmpty(address)) {
            return Result.error(Result.SELECT_ERROR);
        } else {
            return Result.success(Result.SELECT_SUCCESS, address);
        }
    }

    @Override
    public Result getDefaultAddress() {
        //先获取当登录用户id
        Long userId = BaseContext.getCurrentId();
        AddressBook defaultAddress = addressBookMapper.getDefaultAddress(userId);
        if (BeanUtil.isEmpty(defaultAddress)) {
            return Result.error(Result.SELECT_ERROR + ",没有找到默认地址");
        } else {
            return Result.success(Result.SELECT_SUCCESS, defaultAddress);
        }
    }

    @Override
    public Result getUserAddressList() {
        //先获取当登录用户id
        Long userId = BaseContext.getCurrentId();
        List<AddressBook> addressList = addressBookMapper.getUserAddressList(userId);
        return Result.success(addressList);
    }

    @Override
    public Result updateInfo(AddressBook addressBook) {
        Boolean info = addressBookMapper.updateInfo(addressBook);
        if (!info) {
            return Result.error(Result.UPDATE_ERROR);
        }
        return Result.success(Result.UPDATE_SUCCESS);
    }
}
